﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;

namespace TfsCommitMonitor
{
	internal static class SerializationHelper
	{
		internal static string Serialize<T>(this T obj)
		{
			try
			{
				var serializer = new DataContractSerializer(obj.GetType());
				using (var writer = new StringWriter())
				{
					var stm = new XmlTextWriter(writer);
					serializer.WriteObject(stm, obj);
					return writer.ToString();
				}
			}
			catch (Exception ex)
			{
				DebugLogger.LogException(ex);
				return null;
			}
		}

		internal static T Deserialize<T>(this String serializedObj)
		{
			try
			{
				var serializer = new DataContractSerializer(typeof(T));
				using (var reader = new StringReader(serializedObj))
				{
					var stm = new XmlTextReader(reader);
					return (T)serializer.ReadObject(stm);
				}
			}
			catch (Exception ex)
			{
				DebugLogger.LogException(ex);
				return default(T);
			}
		}
	}
}
